package com.pig4cloud.pig.module.controller.estate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.pig4cloud.pig.admin.api.dto.UserInfo;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.estate.EstateUser;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.estate.IEstateUserService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

/**
 * 商家的管理用户wxuser的用户Controller
 *
 * @author ruoyi
 * @date 2022-04-27
 */
@Validated
@Api(value = "商家的管理用户wxuser的用户控制器", tags = {"商家的管理用户wxuser的用户管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/estate/user")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class EstateUserController  {

    private final IEstateUserService estateUserService;
	private final IWxUserService wxUserService;
	private final RemoteUserService remoteUserService;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询商家的管理用户wxuser的用户列表
     */
    @ApiOperation("查询商家的管理用户wxuser的用户列表")
    @PreAuthorize("@pms.hasPermission('module:estateUser:list')")
    @GetMapping("/list")
    public TableDataInfo<EstateUser> list(@Validated EstateUser estateUser) {
        QueryWrapper<EstateUser> qw = new QueryWrapper<>();
        if(estateUser.getEstateId()!=null){
        	qw.eq("estate_id",estateUser.getEstateId());
		}
		if(estateUser.getSysUserId()!=null){
			qw.eq("sys_user_id",estateUser.getSysUserId());
		}

        TableDataInfo<EstateUser> td = PageUtils.buildDataInfo(estateUserService.page(PageUtils.buildPage(),qw));
        List<EstateUser> list = td.getData();
		if(CollUtil.isNotEmpty(list)){
			for (EstateUser merUser1 : list){
				R<UserInfo> result = remoteUserService.userDetail(merUser1.getSysUserId(), SecurityConstants.FROM_IN);
				SysUser sysUser = result.getData().getSysUser();
				if(sysUser!=null){
					merUser1.setSysUserName(sysUser.getName());
				}
				WxUser wxUser = wxUserService.getById(merUser1.getUserId());
				if(wxUser!=null){
					merUser1.setWxUserName(EmojiParser.parseToUnicode(wxUser.getNickName()));
					merUser1.setFaceUrl(wxUser.getFaceUrl());
					if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
						merUser1.setFaceUrl(imgUrl + wxUser.getFaceUrl());
					}
				}
			}
		}
        return td;
    }

    /**
     * 获取商家的管理用户wxuser的用户详细信息
     */
    @ApiOperation("获取商家的管理用户wxuser的用户详细信息")
    @PreAuthorize("@pms.hasPermission('module:estateUser:query')")
    @GetMapping("/{id}")
    public R<EstateUser> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        EstateUser estateUser = estateUserService.getById(id);
        return R.ok(estateUser);
    }

    /**
     * 新增商家的管理用户wxuser的用户
     */
    @ApiOperation("新增商家的管理用户wxuser的用户")
    @PreAuthorize("@pms.hasPermission('module:estateUser:add')")
    @SysLog("商家的管理用户wxuser的用户")
    @PostMapping()
    public R<Void> add(@Valid @RequestBody EstateUser estateUser) {
    	boolean bl = false;
    	QueryWrapper<EstateUser> qw = new QueryWrapper<>();
    	qw.eq("estate_id",estateUser.getEstateId());
		qw.eq("sys_user_id",estateUser.getSysUserId());
//		qw.eq("user_id",estateUser.getUserId());
		qw.and(wrapper->{
			wrapper.eq("user_id",0).or().isNull("user_id");
		});
		qw.last("limit 1");
		qw.orderByAsc("id");
		EstateUser user = estateUserService.getOne(qw);
		if(user != null){
			user.setUserId(estateUser.getUserId());
			bl = estateUserService.updateById(user);
			if(bl){
				return R.ok();
			}else{
				return R.failed("添加失败");
			}
		}else{
			user = new EstateUser();
			user.setEstateId(estateUser.getEstateId());
			user.setSysUserId(estateUser.getSysUserId());
			user.setUserId(estateUser.getUserId());
			user.setCreateTime(new Date());
			user.setNickName(estateUser.getNickName());
			user.setIsManager(0);
			user.setState(1);
			bl = estateUserService.save(user);
			if(bl){
				return R.ok();
			}else{
				return R.failed("添加失败");
			}
		}
//		return R.success("该用户已存在");
    }

    /**
     * 修改商家的管理用户wxuser的用户
     */
    @ApiOperation("修改商家的管理用户wxuser的用户")
    @PreAuthorize("@pms.hasPermission('module:estateUser:edit')")
    @SysLog("商家的管理用户wxuser的用户")
    @PutMapping()
    public R<Void> edit(@Valid @RequestBody EstateUser estateUser) {
        return R.okByRow(estateUserService.updateById(estateUser) ? 1 : 0);
    }



	/**
	 * 修改商家的管理用户wxuser的用户
	 */
	@ApiOperation("修改商家的管理用户wxuser的用户")
	@PreAuthorize("@pms.hasPermission('module:estateUser:edit')")
	@SysLog("商家的管理用户wxuser的用户")
	@PostMapping("/updateManager")
	public R<Void> updateManager(@Valid @RequestBody EstateUser estateUser) {

		estateUserService.update(new LambdaUpdateWrapper<EstateUser>()
			.set(EstateUser::getIsManager,0)
			.eq(EstateUser::getEstateId,estateUser.getEstateId()));

		estateUser.setIsManager(1);
		return R.okByRow(estateUserService.updateById(estateUser) ? 1 : 0);
	}

	/**
     * 删除商家的管理用户wxuser的用户
     */
    @ApiOperation("删除商家的管理用户wxuser的用户")
    @PreAuthorize("@pms.hasPermission('module:estateUser:remove')")
    @SysLog("商家的管理用户wxuser的用户")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
		boolean bl = false;
    	for (Integer id : ids){
			EstateUser estateUser = estateUserService.findById(id);
			if(estateUser!=null){
				QueryWrapper<EstateUser> qw = new QueryWrapper<>();
				qw.eq("estate_id",estateUser.getEstateId());
				qw.eq("sys_user_id",estateUser.getSysUserId());
				long count = estateUserService.count(qw);
				if(count > 1){
					bl = estateUserService.removeById(estateUser.getId());
				}else{
					estateUser.setUserId(0);
					bl = estateUserService.updateById(estateUser);
				}
			}
		}
        return R.okByRow(bl ? 1 : 0);
    }
}
